//
//  OAuthViewController.swift
//  WeiboDemo
//
//  Created by Quentin Zang on 2020/3/15.
//  Copyright © 2020 臧乾坤. All rights reserved.
//

import UIKit
import WebKit

///  用户登录控制器
class OAuthViewController: UIViewController {
    
    private lazy var wkWebView = WKWebView()
    
    // MARK: - 监听方法
    @objc private func close() {
        dismiss(animated: true, completion: nil)
    }
    
    /// 自动填充用户名和密码 - web 注入
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value = 'daoge10000@sina.cn';" + "document.getElementById('passwd').value = 'qq123';"
        // 让 wkwebView执行js
        let config = WKWebViewConfiguration()
        config.userContentController = WKUserContentController()
        let jsUserScript = WKUserScript(source: js, injectionTime: .atDocumentStart, forMainFrameOnly: false)
        config.userContentController.addUserScript(jsUserScript)
        
        acceptCode()
    }
    
    // MARK: - 设置界面
    override func loadView() {
        view = wkWebView
        
        // 设置代理
        //wkWebView.uiDelegate = self as? WKUIDelegate
        
        //设置导航栏
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: #selector(autoFill))
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 在开发中，如果用纯代码开发，视图最好都指定背景颜色，如果为nil，会影响渲染效率
        //view.backgroundColor = .white
        // 加载页面
        self.wkWebView.load(URLRequest(url: NetworkTools.sharedTools.oauthUrl))
    }
    
    
    func acceptCode() -> Void {
//        NetworkTools.sharedTools.loadAccessToken(code: "2.00eJrK1EuhOQKE23643e02e1CaJBiB") { (result, error) in
//            if error != nil {
//                print("出错了")
//                return
//            }
//
//            // 输出结果
//            print(result)
//
//        }
        
        let results = ["access_token":"2.00ml8IrF6dP8NEb33e7215aeRhcdB",
                   "expires_in":"157679999",
                   
                   "uid":"5365823342"]
                   
                   // 在swift中任何any类型必须转换-> as?/! 类型
                   let account = UserAccount(dict: results as [String : Any])
                   print(account)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
